/*
 * OBSUserGUI.java
 *
 * Created on 23-11-2010, 11:13:05
 */

package GUI;

import OBS.SystemMailer;
import OBS.SystemToHTML;
import Databasehandler.DBCommunicator;
import Databasehandler.DBConnector;
import Databasehandler.MySQLCommunicator;
import Errorhandler.ErrorLogger;
import OBS.Customer;
import OBS.OBSUser;
import OBS.OBSReportSubscriber;
import java.io.File;

/**
 *
 * Evt. fejl skrives til error log. Dog kan der opstå en fejl der ikke kan
 * logges hvis der ikke er skriverettighed til log bibliotektet. Det er
 * Organisators driftafdelings opgave at sikre at der til enhver tid er skrive-
 * rettighed til log biblioteket. Alternativ kan der skrives til OS event log,
 * det rette sted at angive den kode er markeret med kommentaren
 * SKRIV_TIL_OS_EVENT_LOG. Organisators drift afdeling vælger selv hvilken
 * løsning de foretrækker og står selv for en eventuel implementering.
 *
 * @author Jesper Wistoft
 */
public class OBSUserGUI extends javax.swing.JFrame {
    private OBSUser obsUser;
    private String logDir = System.getProperty("user.dir") + File.separator+"log"+File.separator;
    private String logName = "OBSUserGUIErrors.log";
    private SystemMailer mailer;

    /** Creates new form OBSUserGUI */
    public OBSUserGUI() {
        initComponents();
        try {
            DBConnector connector = new DBConnector();
            DBCommunicator communicator = new MySQLCommunicator(connector);
            obsUser = new OBSUser(communicator);
        }
        catch(Exception e) {
            ShowPopUp.showMessage("Databasefejl: " + e.getMessage() + " \n Kontakt Driften");
             // send fejlmeddelse til ErrorLog
            try {
                ErrorLogger.writeToErrorLog(logDir+logName,"Databasefejl: " + e.getMessage());
            } catch (Exception e1){} // fejl hvis der ikke kan skrives til log kan ikke håndteres, SKRIV_TIL_OS_EVENT_LOG
            System.exit(0);
        }

        try {
            mailer = new SystemMailer();
        }
        catch(Exception e) {
            ShowPopUp.showMessage("Kun ikke indlæse mail server konfiguration: " + e.getMessage() + " \n Kontakt Driften");
             // send fejlmeddelse til ErrorLog
            try {
                ErrorLogger.writeToErrorLog(logDir+logName,"Mail server config kunne ikke indlæses: " + e.getMessage());
            } catch (Exception e1){} // fejl hvis der ikke kan skrives til log kan ikke håndteres, SKRIV_TIL_OS_EVENT_LOG
        }

        updateCustomerList();
        updateSubscriberList();
        showBatchReportsCustomer();
    }

    public void updateCustomerList() {
        try {
            Object[] c = obsUser.getCurrentCustomers();
            Object[] items = new Object[c.length + 1];
            if(c.length == 0) {
                items[0] = "Ingen";
            }

            System.arraycopy(c, 0, items, 0, c.length);
            customerList.setListData(items);
            customerList.setSelectedIndex(0);
        }
        catch(Exception e) {
            ShowPopUp.showMessage("Programfejl: " + e.getMessage() + " \n Kontakt Driften");
             // send fejlmeddelse til ErrorLog
            try {
                ErrorLogger.writeToErrorLog(logDir+logName,"Programfejl: " + e.getMessage());
            } catch (Exception e1){} // fejl hvis der ikke kan skrives til log kan ikke håndteres, SKRIV_TIL_OS_EVENT_LOG
        }
    }

    public void updateSubscriberList() {
        try {
            Object c = customerList.getSelectedValue();
            Object[] items = new Object[1];
            if(c == null || c.equals("Ingen")) {
                items[0] = "Ingen";
            }
            else {
                Customer customer = (Customer)c;
                OBSReportSubscriber[] OBSReportSubscribers = customer.getOBSReportSubscribers();
                if(OBSReportSubscribers.length == 0) {
                    items[0] = "Ingen";
                }
                else {
                    items = OBSReportSubscribers;
                }
            }
            subscriberList.setListData(items);
            //subscriberList.setSelectedIndex(0);
        }
        catch(Exception e) {
            ShowPopUp.showMessage("Programfejl: " + e.getMessage() + " \n Kontakt Driften");
            // send fejlmeddelse til ErrorLog
            try {
                ErrorLogger.writeToErrorLog(logDir+logName,"Programfejl: " + e.getMessage());
            } catch (Exception e1){} // fejl hvis der ikke kan skrives til log kan ikke håndteres, SKRIV_TIL_OS_EVENT_LOG
        }
    }

    public void showBatchReportsCustomer() {
     String output="";
      try {
            Object c = customerList.getSelectedValue();
            if(c == null || c.equals("Ingen")) {
                output = "Ingen kunde valgt";
            }
            else {
                Customer customer = (Customer)c;
                output = SystemToHTML.generateHTML(customer);
            }
             batchReportsTxtPane.setContentType("text/html");
             batchReportsTxtPane.setText(output);
        }
        catch(Exception e) {
            ShowPopUp.showMessage("Programfejl: " + e.getMessage() + " \n Kontakt Driften");
            // send fejlmeddelse til ErrorLog
            try {
                ErrorLogger.writeToErrorLog(logDir+logName,"Programfejl: " + e.getMessage());
            } catch (Exception e1){} // fejl hvis der ikke kan skrives til log kan ikke håndteres, SKRIV_TIL_OS_EVENT_LOG
        }
    }

    public void showBatchReportsSubscriber() {
     String output="";
      try {
            Object c = subscriberList.getSelectedValue();
            if(c == null || c.equals("Ingen")) {
                output = "Ingen abonnent";
            }
            else {
                OBSReportSubscriber subscriber = (OBSReportSubscriber)c;
                output = SystemToHTML.generateHTML(subscriber);
            }
             batchReportsTxtPane.setContentType("text/html");
             batchReportsTxtPane.setText(output);
        }
        catch(Exception e) {
            ShowPopUp.showMessage("Programfejl: " + e.getMessage() + " \n Kontakt Driften");
            // send fejlmeddelse til ErrorLog
            try {
                ErrorLogger.writeToErrorLog(logDir+logName,"Programfejl: " + e.getMessage());
            } catch (Exception e1){} // fejl hvis der ikke kan skrives til log kan ikke håndteres, SKRIV_TIL_OS_EVENT_LOG
        }
    }

    public void sendMailCustomer() {
        try {
            Object c =  customerList.getSelectedValue();
            if(c == null || c.equals("Ingen")) {
                ShowPopUp.showMessage("Ingen kunde valgt");
            }
            else {
                Customer customer = (Customer)c;
                mailer.sendMail(customer);
            }
      }
        catch(Exception e) {
            ShowPopUp.showMessage("Programfejl: " + e.getMessage() + " \n Kontakt Driften");
            // send fejlmeddelse til ErrorLog
            try {
                ErrorLogger.writeToErrorLog(logDir+logName,"Programfejl: " + e.getMessage());
            } catch (Exception e1){} // fejl hvis der ikke kan skrives til log kan ikke håndteres, SKRIV_TIL_OS_EVENT_LOG
        }
    }

    public void sendMailSubscriber() {
      try {
            Object c = subscriberList.getSelectedValue();
            if(c == null || c.equals("Ingen")) {
                ShowPopUp.showMessage("Ingen abonnent valgt");
            }
            else {
                OBSReportSubscriber subscriber = (OBSReportSubscriber)c;
                mailer.sendMail(subscriber);
            }
      }
        catch(Exception e) {
            ShowPopUp.showMessage("Programfejl: " + e.getMessage() + " \n Kontakt Driften");
            // send fejlmeddelse til ErrorLog
            try {
                ErrorLogger.writeToErrorLog(logDir+logName,"Programfejl: " + e.getMessage());
            } catch (Exception e1){} // fejl hvis der ikke kan skrives til log kan ikke håndteres, SKRIV_TIL_OS_EVENT_LOG
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        customerList = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        subscriberList = new javax.swing.JList();
        sendCustomerMailButton = new javax.swing.JButton();
        customerLabel = new javax.swing.JLabel();
        subscriberLabel = new javax.swing.JLabel();
        batchReportLabel = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        batchReportsTxtPane = new javax.swing.JTextPane();
        sendSubsrciberMail = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        customerList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Kunde" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        customerList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        customerList.setMaximumSize(new java.awt.Dimension(50, 80));
        customerList.setMinimumSize(new java.awt.Dimension(50, 80));
        customerList.setPreferredSize(new java.awt.Dimension(50, 80));
        customerList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                customerListMousePressed(evt);
            }
        });
        customerList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                customerListKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(customerList);

        subscriberList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Abonnent" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        subscriberList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        subscriberList.setPreferredSize(new java.awt.Dimension(35, 80));
        subscriberList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                subscriberListMousePressed(evt);
            }
        });
        subscriberList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                subscriberListKeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(subscriberList);

        sendCustomerMailButton.setText("Send mails til valgt kunde");
        sendCustomerMailButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendCustomerMailButtonActionPerformed(evt);
            }
        });

        customerLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
        customerLabel.setText("Aktuelle Kunder");

        subscriberLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
        subscriberLabel.setText("Abonnenter");

        batchReportLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
        batchReportLabel.setText("Batch Rapporter");

        batchReportsTxtPane.setBorder(null);
        batchReportsTxtPane.setEditable(false);
        batchReportsTxtPane.setMargin(new java.awt.Insets(10, 50, 10, 10));
        jScrollPane3.setViewportView(batchReportsTxtPane);

        sendSubsrciberMail.setText("Send mail til valgt abonnent");
        sendSubsrciberMail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendSubsrciberMailActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(batchReportLabel)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(sendCustomerMailButton, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(customerLabel))
                        .addGap(206, 206, 206)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(sendSubsrciberMail, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE))
                            .addComponent(subscriberLabel))
                        .addGap(21, 21, 21))))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 1164, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(subscriberLabel)
                            .addComponent(customerLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(batchReportLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(67, 67, 67)
                        .addComponent(sendCustomerMailButton, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(131, 131, 131))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(67, 67, 67)
                        .addComponent(sendSubsrciberMail, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(131, 131, 131)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void sendCustomerMailButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendCustomerMailButtonActionPerformed
        sendMailCustomer();
    }//GEN-LAST:event_sendCustomerMailButtonActionPerformed

    private void sendSubsrciberMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendSubsrciberMailActionPerformed
        sendMailSubscriber();
    }//GEN-LAST:event_sendSubsrciberMailActionPerformed

    private void customerListMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_customerListMousePressed
        updateSubscriberList();
        showBatchReportsCustomer();
    }//GEN-LAST:event_customerListMousePressed

    private void subscriberListMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_subscriberListMousePressed
        showBatchReportsSubscriber();
    }//GEN-LAST:event_subscriberListMousePressed

    private void customerListKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_customerListKeyReleased
        updateSubscriberList();
        showBatchReportsCustomer();
    }//GEN-LAST:event_customerListKeyReleased

    private void subscriberListKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_subscriberListKeyReleased
        showBatchReportsSubscriber();
    }//GEN-LAST:event_subscriberListKeyReleased

    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel batchReportLabel;
    private javax.swing.JTextPane batchReportsTxtPane;
    private javax.swing.JLabel customerLabel;
    private javax.swing.JList customerList;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton sendCustomerMailButton;
    private javax.swing.JButton sendSubsrciberMail;
    private javax.swing.JLabel subscriberLabel;
    private javax.swing.JList subscriberList;
    // End of variables declaration//GEN-END:variables

}
